<?php
require_once '../config/database.php';
require_once '../includes/operation_logger.php';

// JSON 响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'admins':
                try {
                    $stmt = $pdo->query("
                        SELECT a.id, a.username, a.real_name, a.email, a.phone, 
                               a.status, a.last_login_time, a.created_at, a.role_id,
                               r.name as role_name, r.display_name as role_display_name
                        FROM admin_users a
                        LEFT JOIN admin_roles r ON a.role_id = r.id
                        ORDER BY a.created_at DESC
                    ");
                    $admins = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型
                    foreach ($admins as &$admin) {
                        $admin['id'] = (int)$admin['id'];
                        $admin['role_id'] = $admin['role_id'] ? (int)$admin['role_id'] : null;
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => ['data' => $admins]
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取管理员失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'roles':
                try {
                    $stmt = $pdo->query("
                        SELECT r.*, 
                               (SELECT COUNT(*) FROM admin_users WHERE role_id = r.id) as user_count
                        FROM admin_roles r 
                        ORDER BY r.is_system DESC, r.created_at ASC
                    ");
                    $roles = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型
                    foreach ($roles as &$role) {
                        $role['id'] = (int)$role['id'];
                        $role['is_system'] = (int)$role['is_system'];
                        $role['user_count'] = (int)$role['user_count'];
                        // 解析权限JSON字符串
                        $role['permissions'] = $role['permissions'] ? json_decode($role['permissions'], true) : [];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $roles
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取角色失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'permissions':
                try {
                    // 返回简化的权限列表
                    $permissions = [
                        '仪表板' => [
                            ['name' => 'dashboard.view', 'display_name' => '查看仪表板', 'description' => '查看统计信息']
                        ],
                        '系统配置' => [
                            ['name' => 'config.view', 'display_name' => '查看配置', 'description' => '查看系统配置'],
                            ['name' => 'config.edit', 'display_name' => '编辑配置', 'description' => '修改系统配置']
                        ],
                        '时段管理' => [
                            ['name' => 'timeslots.view', 'display_name' => '查看时段', 'description' => '查看时段列表'],
                            ['name' => 'timeslots.edit', 'display_name' => '编辑时段', 'description' => '添加修改删除时段']
                        ],
                        '闭馆设置' => [
                            ['name' => 'closures.view', 'display_name' => '查看闭馆', 'description' => '查看闭馆设置'],
                            ['name' => 'closures.edit', 'display_name' => '编辑闭馆', 'description' => '添加修改删除闭馆规则']
                        ],
                        '预约管理' => [
                            ['name' => 'reservations.view', 'display_name' => '查看预约', 'description' => '查看预约列表'],
                            ['name' => 'reservations.edit', 'display_name' => '编辑预约', 'description' => '修改预约状态']
                        ],
                        '用户管理' => [
                            ['name' => 'users.view', 'display_name' => '查看用户', 'description' => '查看微信用户列表'],
                            ['name' => 'users.edit', 'display_name' => '编辑用户', 'description' => '修改用户状态']
                        ],
                        '核验中心' => [
                            ['name' => 'verification.view', 'display_name' => '查看核验', 'description' => '查看核验记录'],
                            ['name' => 'verification.edit', 'display_name' => '执行核验', 'description' => '执行预约核验和签到']
                        ],
                        '活动管理' => [
                            ['name' => 'activities.view', 'display_name' => '查看活动申请', 'description' => '查看活动申请列表'],
                            ['name' => 'activities.edit', 'display_name' => '审核活动申请', 'description' => '审核、批准或拒绝活动申请']
                        ],
                        '管理员' => [
                            ['name' => 'admin.view', 'display_name' => '查看管理员', 'description' => '查看管理员列表'],
                            ['name' => 'admin.edit', 'display_name' => '编辑管理员', 'description' => '添加修改删除管理员']
                        ],
                        '角色管理' => [
                            ['name' => 'roles.view', 'display_name' => '查看角色', 'description' => '查看角色列表'],
                            ['name' => 'roles.edit', 'display_name' => '编辑角色', 'description' => '添加修改删除角色']
                        ],
                        '系统日志' => [
                            ['name' => 'logs.view', 'display_name' => '查看日志', 'description' => '查看系统日志']
                        ]
                    ];
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $permissions
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取权限失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'login_logs':
                try {
                    $stmt = $pdo->query("
                        SELECT l.*, a.username 
                        FROM admin_login_logs l 
                        LEFT JOIN admin_users a ON l.admin_id = a.id 
                        ORDER BY l.created_at DESC 
                        LIMIT 50
                    ");
                    $logs = $stmt->fetchAll();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $logs
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取登录日志失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'operation_logs':
                try {
                    $stmt = $pdo->query("
                        SELECT l.*, a.username 
                        FROM admin_operation_logs l 
                        LEFT JOIN admin_users a ON l.admin_id = a.id 
                        ORDER BY l.created_at DESC 
                        LIMIT 50
                    ");
                    $logs = $stmt->fetchAll();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $logs
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取操作日志失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'users':
                try {
                    // 获取微信用户列表，包含预约统计和核销员状态
                    $stmt = $pdo->query("
                        SELECT u.*, 
                               COUNT(r.id) as reservation_count,
                               CASE WHEN u.is_active = 1 THEN 'active' ELSE 'inactive' END as status,
                               COALESCE(u.is_verifier, 0) as is_verifier
                        FROM users u
                        LEFT JOIN reservations r ON u.id = r.user_id
                        GROUP BY u.id
                        ORDER BY u.created_at DESC
                    ");
                    $users = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型，添加字段映射
                    foreach ($users as &$user) {
                        $user['id'] = (int)$user['id'];
                        $user['reservation_count'] = (int)$user['reservation_count'];
                        $user['is_verifier'] = (int)$user['is_verifier'];
                        $user['username'] = $user['nickname']; // 兼容前端字段名
                        $user['avatar_url'] = $user['avatar']; // 微信头像字段
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $users
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取微信用户失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'search_users':
                try {
                    $keyword = $_GET['keyword'] ?? '';
                    if (empty($keyword)) {
                        sendJson([
                            'code' => 400,
                            'message' => '搜索关键词不能为空',
                            'data' => null
                        ]);
                    }
                    
                    $searchTerm = '%' . $keyword . '%';
                    $stmt = $pdo->prepare("
                        SELECT u.*, 
                               COUNT(r.id) as reservation_count,
                               CASE WHEN u.is_active = 1 THEN 'active' ELSE 'inactive' END as status,
                               COALESCE(u.is_verifier, 0) as is_verifier
                        FROM users u
                        LEFT JOIN reservations r ON u.id = r.user_id
                        WHERE u.nickname LIKE ? 
                           OR u.real_name LIKE ? 
                           OR u.phone LIKE ?
                        GROUP BY u.id
                        ORDER BY u.created_at DESC
                    ");
                    $stmt->execute([$searchTerm, $searchTerm, $searchTerm]);
                    $users = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型，添加字段映射
                    foreach ($users as &$user) {
                        $user['id'] = (int)$user['id'];
                        $user['reservation_count'] = (int)$user['reservation_count'];
                        $user['is_verifier'] = (int)$user['is_verifier'];
                        $user['username'] = $user['nickname']; // 兼容前端字段名
                        $user['avatar_url'] = $user['avatar']; // 微信头像字段
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '搜索成功',
                        'data' => $users
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '搜索微信用户失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'user_detail':
                try {
                    $userId = (int)($_GET['id'] ?? 0);
                    if (!$userId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少用户ID',
                            'data' => null
                        ]);
                    }
                    
                    // 获取用户基本信息
                    $stmt = $pdo->prepare("
                        SELECT u.*, 
                               COUNT(r.id) as reservation_count,
                               CASE WHEN u.status = 1 THEN 'active' ELSE 'inactive' END as status
                        FROM users u
                        LEFT JOIN reservations r ON u.id = r.user_id
                        WHERE u.id = ?
                        GROUP BY u.id
                    ");
                    $stmt->execute([$userId]);
                    $user = $stmt->fetch();
                    
                    if (!$user) {
                        sendJson([
                            'code' => 404,
                            'message' => '用户不存在',
                            'data' => null
                        ]);
                    }
                    
                    // 获取最近预约记录
                    $stmt = $pdo->prepare("
                        SELECT r.*, 
                               mts.slot_name,
                               mts.start_time,
                               mts.end_time
                        FROM reservations r
                        LEFT JOIN museum_time_slots mts ON r.time_slot_id = mts.id
                        WHERE r.user_id = ?
                        ORDER BY r.created_at DESC
                        LIMIT 10
                    ");
                    $stmt->execute([$userId]);
                    $recent_reservations = $stmt->fetchAll();
                    
                    // 数据处理
                    $user['id'] = (int)$user['id'];
                    $user['reservation_count'] = (int)$user['reservation_count'];
                    $user['username'] = $user['nickname']; // 兼容前端字段名
                    $user['avatar_url'] = $user['avatar']; // 微信头像字段
                    $user['recent_reservations'] = $recent_reservations;
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $user
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取用户详情失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'activities':
                try {
                    // 获取活动申请列表
                    $stmt = $pdo->query("
                        SELECT a.*, 
                               u.nickname as applicant_nickname,
                               u.real_name as applicant_real_name
                        FROM activity_applications a
                        LEFT JOIN users u ON a.user_id = u.id
                        ORDER BY a.created_at DESC
                    ");
                    $activities = $stmt->fetchAll();
                    
                    // 处理数据
                    foreach ($activities as &$activity) {
                        $activity['id'] = (int)$activity['id'];
                        $activity['user_id'] = (int)$activity['user_id'];
                        $activity['participant_count'] = (int)$activity['participant_count'];
                        $activity['custom_fields'] = $activity['custom_fields'] ? json_decode($activity['custom_fields'], true) : [];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $activities
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取活动申请失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'search_activities':
                try {
                    $keyword = $_GET['keyword'] ?? '';
                    $status = $_GET['status'] ?? '';
                    $type = $_GET['type'] ?? '';
                    $date = $_GET['date'] ?? '';
                    
                    // 构建WHERE条件
                    $whereConditions = [];
                    $params = [];
                    
                    // 关键词搜索
                    if (!empty($keyword)) {
                        $searchTerm = '%' . $keyword . '%';
                        $whereConditions[] = "(a.activity_name LIKE ? OR a.contact_name LIKE ? OR a.organizer LIKE ?)";
                        $params[] = $searchTerm;
                        $params[] = $searchTerm;
                        $params[] = $searchTerm;
                    }
                    
                    // 状态筛选
                    if (!empty($status) && is_numeric($status)) {
                        $whereConditions[] = "a.status = ?";
                        $params[] = (int)$status;
                    }
                    
                    // 活动类型筛选
                    if (!empty($type)) {
                        $whereConditions[] = "a.activity_type = ?";
                        $params[] = $type;
                    }
                    
                    // 活动日期筛选
                    if (!empty($date)) {
                        $whereConditions[] = "a.activity_date = ?";
                        $params[] = $date;
                    }
                    
                    // 如果没有任何筛选条件，返回所有数据
                    $whereClause = empty($whereConditions) ? "1=1" : implode(' AND ', $whereConditions);
                    
                    $sql = "
                        SELECT a.*, 
                               u.nickname as applicant_nickname,
                               u.real_name as applicant_real_name
                        FROM activity_applications a
                        LEFT JOIN users u ON a.user_id = u.id
                        WHERE {$whereClause}
                        ORDER BY a.created_at DESC
                    ";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $activities = $stmt->fetchAll();
                    
                    // 处理数据
                    foreach ($activities as &$activity) {
                        $activity['id'] = (int)$activity['id'];
                        $activity['user_id'] = (int)$activity['user_id'];
                        $activity['participant_count'] = (int)$activity['participant_count'];
                        $activity['custom_fields'] = $activity['custom_fields'] ? json_decode($activity['custom_fields'], true) : [];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '搜索成功',
                        'data' => $activities
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '搜索活动申请失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'activity_detail':
                try {
                    $activityId = (int)($_GET['id'] ?? 0);
                    if (!$activityId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少活动ID',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("
                        SELECT a.*, 
                               u.nickname as applicant_nickname,
                               u.real_name as applicant_real_name,
                               u.phone as applicant_phone
                        FROM activity_applications a
                        LEFT JOIN users u ON a.user_id = u.id
                        WHERE a.id = ?
                    ");
                    $stmt->execute([$activityId]);
                    $activity = $stmt->fetch();
                    
                    if (!$activity) {
                        sendJson([
                            'code' => 404,
                            'message' => '活动申请不存在',
                            'data' => null
                        ]);
                    }
                    
                    // 处理数据
                    $activity['id'] = (int)$activity['id'];
                    $activity['user_id'] = (int)$activity['user_id'];
                    $activity['participant_count'] = (int)$activity['participant_count'];
                    $activity['custom_fields'] = $activity['custom_fields'] ? json_decode($activity['custom_fields'], true) : [];
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $activity
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取活动详情失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'custom_fields':
                try {
                    // 获取自定义字段配置
                    $stmt = $pdo->query("
                        SELECT * FROM activity_custom_fields 
                        WHERE is_active = 1 
                        ORDER BY sort_order ASC
                    ");
                    $fields = $stmt->fetchAll();
                    
                    foreach ($fields as &$field) {
                        $field['id'] = (int)$field['id'];
                        $field['field_options'] = $field['field_options'] ? json_decode($field['field_options'], true) : [];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $fields
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取自定义字段失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'create_admin':
                try {
                    if (!isset($input['username']) || !isset($input['password']) || !isset($input['role_id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '用户名、密码和角色不能为空',
                            'data' => null
                        ]);
                    }
                    
                    $username = trim($input['username']);
                    $password = $input['password'];
                    $realName = trim($input['real_name'] ?? '');
                    $email = trim($input['email'] ?? '');
                    $roleId = (int)$input['role_id'];
                    
                    // 检查用户名是否已存在
                    $stmt = $pdo->prepare("SELECT id FROM admin_users WHERE username = ?");
                    $stmt->execute([$username]);
                    if ($stmt->fetch()) {
                        sendJson([
                            'code' => 400,
                            'message' => '用户名已存在',
                            'data' => null
                        ]);
                    }
                    
                    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                    
                    $stmt = $pdo->prepare("
                        INSERT INTO admin_users (username, password, real_name, email, role_id, status, created_at) 
                        VALUES (?, ?, ?, ?, ?, 'active', NOW())
                    ");
                    
                    $result = $stmt->execute([$username, $passwordHash, $realName, $email, $roleId]);
                    
                    if ($result) {
                        $id = $pdo->lastInsertId();
                        sendJson([
                            'code' => 200,
                            'message' => '创建成功',
                            'data' => ['id' => $id]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '创建失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '创建管理员失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'create_role':
                try {
                    if (!isset($input['name']) || !isset($input['display_name'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '角色名称不能为空',
                            'data' => null
                        ]);
                    }
                    
                    $name = trim($input['name']);
                    $displayName = trim($input['display_name']);
                    $description = trim($input['description'] ?? '');
                    $permissions = $input['permissions'] ?? [];
                    
                    // 检查角色名是否已存在
                    $stmt = $pdo->prepare("SELECT id FROM admin_roles WHERE name = ?");
                    $stmt->execute([$name]);
                    if ($stmt->fetch()) {
                        sendJson([
                            'code' => 400,
                            'message' => '角色名称已存在',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("
                        INSERT INTO admin_roles (name, display_name, description, permissions, is_system, status, created_at) 
                        VALUES (?, ?, ?, ?, 0, 'active', NOW())
                    ");
                    
                    $result = $stmt->execute([$name, $displayName, $description, json_encode($permissions)]);
                    
                    if ($result) {
                        $id = $pdo->lastInsertId();
                        sendJson([
                            'code' => 200,
                            'message' => '创建成功',
                            'data' => ['id' => $id]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '创建失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '创建角色失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'set_verifier':
                try {
                    if (!isset($input['user_id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少用户ID',
                            'data' => null
                        ]);
                    }
                    
                    $userId = (int)$input['user_id'];
                    $isVerifier = isset($input['is_verifier']) ? (int)$input['is_verifier'] : 1;
                    
                    // 检查用户是否存在
                    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
                    $stmt->execute([$userId]);
                    if (!$stmt->fetch()) {
                        sendJson([
                            'code' => 400,
                            'message' => '用户不存在',
                            'data' => null
                        ]);
                    }
                    
                    // 更新用户核销员状态
                    $stmt = $pdo->prepare("UPDATE users SET is_verifier = ? WHERE id = ?");
                    $result = $stmt->execute([$isVerifier, $userId]);
                    
                    if ($result) {
                        sendJson([
                            'code' => 200,
                            'message' => $isVerifier ? '设置核销员成功' : '取消核销员成功',
                            'data' => ['user_id' => $userId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '操作失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '设置核销员失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'update_admin':
                try {
                    if (!isset($input['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少管理员ID',
                            'data' => null
                        ]);
                    }
                    
                    $adminId = (int)$input['id'];
                    $updateData = [];
                    $params = [];
                    
                    // 构建更新字段
                    if (isset($input['real_name'])) {
                        $updateData[] = 'real_name = ?';
                        $params[] = trim($input['real_name']);
                    }
                    if (isset($input['email'])) {
                        $updateData[] = 'email = ?';
                        $params[] = trim($input['email']);
                    }
                    if (isset($input['role_id'])) {
                        $updateData[] = 'role_id = ?';
                        $params[] = (int)$input['role_id'];
                    }
                    if (isset($input['status'])) {
                        $updateData[] = 'status = ?';
                        $params[] = $input['status'];
                    }
                    
                    if (empty($updateData)) {
                        sendJson([
                            'code' => 400,
                            'message' => '没有要更新的字段',
                            'data' => null
                        ]);
                    }
                    
                    $updateData[] = 'updated_at = NOW()';
                    $params[] = $adminId;
                    
                    $sql = "UPDATE admin_users SET " . implode(', ', $updateData) . " WHERE id = ?";
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '更新成功',
                            'data' => ['id' => $adminId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '更新失败，管理员可能不存在或没有变化',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新管理员失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'update_role':
                try {
                    if (!isset($input['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少角色ID',
                            'data' => null
                        ]);
                    }
                    
                    $roleId = (int)$input['id'];
                    
                    // 检查角色是否存在以及是否为系统角色
                    $stmt = $pdo->prepare("SELECT is_system FROM admin_roles WHERE id = ?");
                    $stmt->execute([$roleId]);
                    $role = $stmt->fetch();
                    
                    if (!$role) {
                        sendJson([
                            'code' => 400,
                            'message' => '角色不存在',
                            'data' => null
                        ]);
                    }
                    
                    $isSystemRole = (int)$role['is_system'] === 1;
                    $updateData = [];
                    $params = [];
                    
                    // 构建更新字段
                    if (isset($input['display_name']) && !$isSystemRole) {
                        $updateData[] = 'display_name = ?';
                        $params[] = trim($input['display_name']);
                    }
                    if (isset($input['description'])) {
                        $updateData[] = 'description = ?';
                        $params[] = trim($input['description']);
                    }
                    if (isset($input['permissions'])) {
                        $updateData[] = 'permissions = ?';
                        $params[] = json_encode($input['permissions']);
                    }
                    if (isset($input['status']) && !$isSystemRole) {
                        $updateData[] = 'status = ?';
                        $params[] = $input['status'];
                    }
                    
                    if (empty($updateData)) {
                        sendJson([
                            'code' => 400,
                            'message' => '没有要更新的字段',
                            'data' => null
                        ]);
                    }
                    
                    $updateData[] = 'updated_at = NOW()';
                    $params[] = $roleId;
                    
                    $sql = "UPDATE admin_roles SET " . implode(', ', $updateData) . " WHERE id = ?";
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '更新成功',
                            'data' => ['id' => $roleId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '更新失败，角色可能不存在或没有变化',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新角色失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'toggle_user_status':
                try {
                    if (!isset($input['user_id']) || !isset($input['status'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少用户ID或状态',
                            'data' => null
                        ]);
                    }
                    
                    $userId = (int)$input['user_id'];
                    $status = $input['status'] === 'active' ? 1 : 0;
                    $statusText = $input['status'] === 'active' ? '启用' : '禁用';
                    
                    // 获取用户信息用于日志
                    $userStmt = $pdo->prepare("SELECT nickname, real_name FROM users WHERE id = ?");
                    $userStmt->execute([$userId]);
                    $user = $userStmt->fetch();
                    $userName = $user ? ($user['real_name'] ?: $user['nickname']) : "ID:$userId";
                    
                    $stmt = $pdo->prepare("UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?");
                    $result = $stmt->execute([$status, $userId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        // 记录操作日志
                        $currentAdmin = getCurrentAdmin($pdo);
                        if ($currentAdmin) {
                            logAdminOperation(
                                $pdo,
                                $currentAdmin[0],
                                $currentAdmin[1],
                                '用户状态变更',
                                'users',
                                "${statusText}用户: $userName",
                                ['user_id' => $userId, 'new_status' => $input['status']]
                            );
                        }
                        
                        sendJson([
                            'code' => 200,
                            'message' => '状态更新成功',
                            'data' => ['id' => $userId, 'status' => $input['status']]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '状态更新失败，用户可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新用户状态失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'update_activity_status':
                try {
                    if (!isset($input['activity_id']) || !isset($input['status'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少活动ID或状态',
                            'data' => null
                        ]);
                    }
                    
                    $activityId = (int)$input['activity_id'];
                    $status = $input['status'];
                    $adminNotes = $input['admin_notes'] ?? '';
                    
                    // 验证状态值并转换为数字
                    $statusMap = [
                        'pending' => 0,
                        'approved' => 1,
                        'rejected' => 2,
                        'cancelled' => 3,
                        'completed' => 1
                    ];
                    
                    if (!in_array($status, array_keys($statusMap))) {
                        sendJson([
                            'code' => 400,
                            'message' => '无效的状态值',
                            'data' => null
                        ]);
                    }
                    
                    $statusValue = $statusMap[$status];
                    
                    // 获取当前管理员信息
                    $currentAdmin = getCurrentAdmin($pdo);
                    $adminId = $currentAdmin ? $currentAdmin[0] : 1; // 回退到默认值
                    
                    // 获取活动信息用于日志
                    $activityStmt = $pdo->prepare("SELECT activity_name FROM activity_applications WHERE id = ?");
                    $activityStmt->execute([$activityId]);
                    $activity = $activityStmt->fetch();
                    $activityName = $activity ? $activity['activity_name'] : "ID:$activityId";
                    
                    $stmt = $pdo->prepare("
                        UPDATE activity_applications 
                        SET status = ?, review_note = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $result = $stmt->execute([$statusValue, $adminNotes, $activityId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        // 记录操作日志
                        if ($currentAdmin) {
                            $statusMap = [
                                'pending' => '待审核',
                                'approved' => '已批准',
                                'rejected' => '已拒绝',
                                'cancelled' => '已取消',
                                'completed' => '已完成'
                            ];
                            $statusText = $statusMap[$status] ?? $status;
                            
                            logAdminOperation(
                                $pdo,
                                $currentAdmin[0],
                                $currentAdmin[1],
                                '活动状态变更',
                                'activities',
                                "将活动「$activityName」状态更改为：$statusText" . ($adminNotes ? "，备注：$adminNotes" : ""),
                                ['activity_id' => $activityId, 'new_status' => $status, 'admin_notes' => $adminNotes]
                            );
                        }
                        sendJson([
                            'code' => 200,
                            'message' => '状态更新成功',
                            'data' => ['id' => $activityId, 'status' => $status]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '状态更新失败，活动申请可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新活动状态失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'DELETE':
        switch ($action) {
            case 'delete_admin':
                try {
                    $adminId = (int)($_GET['id'] ?? 0);
                    if (!$adminId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少管理员ID',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id = ?");
                    $result = $stmt->execute([$adminId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '删除成功',
                            'data' => ['id' => $adminId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '删除失败，管理员可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '删除管理员失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'delete_role':
                try {
                    $roleId = (int)($_GET['id'] ?? 0);
                    if (!$roleId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少角色ID',
                            'data' => null
                        ]);
                    }
                    
                    // 检查是否有管理员在使用该角色
                    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM admin_users WHERE role_id = ?");
                    $stmt->execute([$roleId]);
                    $userCount = $stmt->fetch();
                    
                    if ($userCount['count'] > 0) {
                        sendJson([
                            'code' => 400,
                            'message' => '该角色下还有管理员，无法删除',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM admin_roles WHERE id = ? AND is_system = 0");
                    $result = $stmt->execute([$roleId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '删除成功',
                            'data' => ['id' => $roleId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '删除失败，角色可能不存在或为系统角色',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '删除角色失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>